import { ref, computed } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import useConfig from '@/utils/apiConfig'
import io from 'socket.io-client'
import { useModalStore } from '@/stores/modalStore'
import { useCurrActStroe } from '@/stores/currActStore'
import type { MsgItems } from '@/types/loginType'
interface ChangeData {
  status: number
  data: { msg: string }
}
export const useSocketStore = defineStore('useSocketStore', () => {
  const { changeData } = useModalStore()
  const config = useConfig()
  const token = localStorage.getItem('token')
  const socket = io(config.baseURL, {
    auth: {
      token: `Bearer ${token}`
    }
  })
  const { currUser } = storeToRefs(useCurrActStroe())

  socket.on('connect', () => {
    socket.on('authSuccess', (data: ChangeData) => changeData(data))
  })

  socket.on('disconnect', () => {
    changeData({ status: 404, data: { msg: '断开了连接' } })
  })

  socket.on('authError', (data: ChangeData) => changeData(data))

  // 发送方法
  function sendMessage(acceptId: string, text: string | null) {
    socket.emit('sendMsg', { acceptId, sendId: currUser.value.id, text })
  }
  // 接收方法
  socket.on('pushMsg', (data) => {
    for (const [key, value] of Object.entries(msgItems.value)) {
      if (key === data.id) {
        msgItems.value[data.id] += 1
      } else {
        msgItems.value[data.id] = 1
      }
    }
    changeData({ status: 200, data: { msg: '接收到新消息' } })
    console.log(msgItems.value)
    console.log(titleItems)
  })

  function userLogout() {
    socket.emit('logout', { userId: currUser.value.id })
  }
  // 消息计数
  const msgItems = ref<MsgItems>({})
  const titleItems = computed(() => {
    let total = 0
    for (const [key, value] of Object.entries(msgItems.value)) {
      total += value
    }
    return total
  })

  return {
    socket,
    msgItems,
    titleItems,
    sendMessage,
    userLogout
  }
})
